import { Form, Input, Button, message } from 'antd'
import {
  UserOutlined,
  LockOutlined
} from '@ant-design/icons';
import { useAppDispatch } from '../../store/hooks';
import { changeName, changeCheckedkeys, changeLoginState, changeRole, changeToken } from '../../store/modules/user';
import { useNavigate } from 'react-router-dom';
import link from '../../apis/link';

export interface IAdminParams {
    adminname: string
    password: string
}

type IndexProps = {}
export const Index = (props: IndexProps) => {
  const dispatch = useAppDispatch()
  const navigate = useNavigate()
  // 点击登录事件
  const onFinish = (values: IAdminParams) => {
    link(`http://localhost:8877/admin?user=${values.adminname}&password=${values.password}`,"get").then(ok=>{
      console.log(ok)
      let {data}=(ok as any);
      if(data.length !== 0){
        message.success("登录成功")
        // 将用户名存入localStorage及状态管理器
        localStorage.setItem('changeName', data[0].user)
        dispatch(changeName(data[0].user))
        // 将权限存入localStorage及状态管理器
        localStorage.setItem('changeRole', data[0].role)
        dispatch(changeRole(data[0].role))
        // 将登入状态存入localStorage及状态管理器
        localStorage.setItem('loginState', 'true')
        localStorage.setItem('role', data[0].role)
        localStorage.setItem('checkedKeys',JSON.stringify(data[0].checkedKeys))
        // localStorage.setItem('checkedKeys', 'true')
        dispatch(changeLoginState(true))
        // 将token存入localStorage及状态管理器
        const token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLCJleHAiOjEzMDA4MTkzODAsImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlLCJvdGhlckZpZWxkIjoiZXRjLiJ9.BkrYadYHS66ZrONzFoA91gBJK0iE-S2ZYOWCpRhgFJQ"
        localStorage.setItem('token', token)
        dispatch(changeToken(token))
        // 跳转到首页
        navigate('/', { replace: true })
      }else{
        message.error("登录失败，请检查输入内容是否正确")
      }
    })
  }
  return (
    <div id='components-form-demo-normal-login'>
      <Form
        name="normal_login"
        className="login-form"
        initialValues={{ remember: true }}
        onFinish={onFinish}
      >
        <h2>按个摩后台管理系统</h2>
        <Form.Item
          name="adminname"
          rules={[{ required: true, message: '请输入管理员账户!' }]}
        >
          <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="管理员账户" allowClear/>
        </Form.Item>
        <Form.Item
          name="password"
          rules={[{ required: true, message: '请输入密码!' }]}
        >
          <Input
            prefix={<LockOutlined className="site-form-item-icon" />}
            type="password"
            placeholder="密码"
            allowClear
          />
        </Form.Item>
    
        <Form.Item>
          <Button type="primary" htmlType="submit" className="login-form-button">
            登 录
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}
